package com.paradogs.gs.modules.inventory;

import com.paradogs.common._cfg.Cfg;
import com.paradogs.common.utils.ObjectUtils;
import com.paradogs.gs.misc.BaseManager;
import com.paradogs.gs.misc.annotations.GameManager;
import com.paradogs.gs.modules.Player;
import com.paradogs.gs.modules.inventory.framework.ItemGainProxyLoader;
import com.paradogs.gs.modules.inventory.framework.ItemType;
import com.paradogs.gs.utils.PlayerUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author: yumi
 * @date: 2024/10/29  15:57
 * @Description: TODO
 */
@Slf4j
@GameManager
public class InventoryMgr extends BaseManager {

    /** 获得和花费道具，消耗失败会自动抛异常 */
    public void update(Map<Integer, Integer> consume, Map<Integer, Integer> gain) {
        if (consume != null && !consume.isEmpty()) {
            consumeItem(consume);
        }
        if (gain != null && !gain.isEmpty()) {
            gainItem(gain);
        }
    }

    public void update(Integer[][] consume, Integer[][] gain) {
        update(ObjectUtils.arr2Map(consume),ObjectUtils.arr2Map(gain));
    }

    // 消耗目前只自动扣减材料背包
    private void consumeItem(Map<Integer, Integer> consume) {
        if (consume == null) {
            return;
        }
        owner().materialMgr().consume(consume);
    }

    private void gainItem(Map<Integer, Integer> gain) {
        for (Map.Entry<Integer, Integer> entry : gain.entrySet()) {
            Integer itemId = entry.getKey();
            Integer count = entry.getValue();
            Method method = ItemGainProxyLoader.ANNOTATION_MAPPING.get(ItemType.get(itemId));
            if (method == null) {
                Cfg.Item cfg = Cfg.Item.get(itemId);
                if (cfg == null) {
                    log.error("道具不存在：{}", itemId);
                } else {
                    log.error("道具[{}]找不到道具类型[{}]的代理方法", itemId, Cfg.Item.get(itemId).itemType());
                }
                continue;
            }
            // 使用代理方法处理道具
            Player player = PlayerUtils.getPlayer(owner().getId());
            try {
                method.invoke(player.getMgr(method.getDeclaringClass()), itemId, count);
            } catch (Exception e) {
                log.error("道具代理方法执行失败：{}, itemId: {}, count: {}, itemType: {}", e.getMessage(), itemId, count, ItemType.get(itemId), e);
            }
        }
    }

}
